package com.lei.zjs.service.ebo;

import java.sql.Timestamp;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.service.CustomerService;

import com.lei.zjs.dao.DecidezoneDao;
import com.lei.zjs.dao.NoticebillDao;
import com.lei.zjs.dao.WorkbillDao;
import com.lei.zjs.service.ebi.NoticebillService;
import com.lei.zjs.vo.Decidedzone;
import com.lei.zjs.vo.Noticebill;
import com.lei.zjs.vo.Staff;
import com.lei.zjs.vo.Workbill;

@Service
@Transactional
public class NoticebillServiceImpl implements NoticebillService {

	@Resource
	private NoticebillDao noticebillDao;
	// 注入远程调用服务接口
	@Resource
	private CustomerService customerService;
	@Resource
	private DecidezoneDao decidezoneDao;
	@Resource
	private WorkbillDao workbillDao;

	@Override
	public void save(Noticebill model) {
		noticebillDao.save(model);
		String decidezoneID = customerService.findDecidezoneIDByAddress(model.getPickaddress());
		if (decidezoneID != null) {
			Decidedzone decidedzone = decidezoneDao.findById(decidezoneID);
			Staff staff = decidedzone.getStaff();
			model.setStaff(staff);
			// 自动分单
			model.setOrdertype("自动");

			Workbill workbill = new Workbill();
			workbill.setAttachbilltimes(0); // 追单次数
			workbill.setBuildtime(new Timestamp(System.currentTimeMillis())); // 建单时间
			workbill.setNoticebill(model); // 业务受理
			workbill.setPickstate("未取件"); // 取件状态
			workbill.setRemark(model.getRemark()); // 备注
			workbill.setStaff(staff); // 取派员
			workbill.setType("新"); // 工作单类型

			workbillDao.save(workbill);
		} else {
			// 人工分单
			model.setOrdertype("人工");
		}
	}

	@Override
	public List<Noticebill> findnoassociations(DetachedCriteria dc) {
		return noticebillDao.findByCriteria(dc);
	}

	@Override
	public void manualDispatch(Noticebill model) {
		Noticebill noticebill = noticebillDao.findById(model.getId());
		Staff staff = new Staff();
		staff.setId(model.getStaff().getId());
		noticebill.setStaff(staff);
		
		Workbill workbill = new Workbill();
		workbill.setAttachbilltimes(0); // 追单次数
		workbill.setBuildtime(new Timestamp(System.currentTimeMillis())); // 建单时间
		workbill.setNoticebill(model); // 业务受理
		workbill.setPickstate("未取件"); // 取件状态
		workbill.setRemark(model.getRemark()); // 备注
		workbill.setStaff(staff);
		workbill.setType("新单"); // 工作单类型
		
		workbill.setNoticebill(noticebill);
		
		workbillDao.save(workbill);
	}

}
